/* **************************************************
 * User Group Manager
 *      author:     Baskin Tapkan
 *          written for Code Plex
 *              April - 2008
 *                  http://tapkan.com
 * ****************************************************
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace UserGroupManager
{
    public partial class EditUser : Form
    {
        string computerName;
        DataSet userInfo;
        int selectedIndex = 0;

        public EditUser(string systemName)
        {
            computerName = systemName;
            InitializeComponent();
            this.Text = "Edit user for " + computerName;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void EditUser_Load(object sender, EventArgs e)
        {
            UserMgr um = new UserMgr();
            um.ComputerName = computerName;
            userInfo = um.GetAllLocalUsers();

            // make sure dataset comes back with records
            if (userInfo.Tables[0].Rows.Count > 0)
            {
                UpdateUI(0);
                for (int i = 0; i < userInfo.Tables[0].Rows.Count; i++)
                    cmbUserName.Items.Add(userInfo.Tables[0].Rows[i]["UserName"].ToString());
                cmbUserName.SelectedIndex = selectedIndex;
            }
        }

        private void UpdateUI(int rowIndex)
        {
            cmbUserName.Text = userInfo.Tables[0].Rows[rowIndex]["UserName"].ToString();
            txtFullName.Text = userInfo.Tables[0].Rows[rowIndex]["FullName"].ToString();
            txtDescription.Text = userInfo.Tables[0].Rows[rowIndex]["Description"].ToString();

            chkAccountDisabled.Checked = Convert.ToBoolean(userInfo.Tables[0].Rows[rowIndex]["AccountDisabled"]);
            chkAccountLockout.Checked = Convert.ToBoolean(userInfo.Tables[0].Rows[rowIndex]["AccountLocked"]);
            chkMustChangePswd.Checked = Convert.ToBoolean(userInfo.Tables[0].Rows[rowIndex]["PasswordLastSet"]);
            chkAccountLockout.Enabled = chkAccountLockout.Checked;
            chkCannotChangePswd.Checked = !Convert.ToBoolean(userInfo.Tables[0].Rows[rowIndex]["PasswordChangeable"]);
            chkPswdNeverExpires.Checked = !Convert.ToBoolean(userInfo.Tables[0].Rows[rowIndex]["PasswordExpires"]);

            EnableDisableMustChangePassword();
            TogglePswdExpiresCannotChangePswd();

            staUserMgr.Items[0].Text = "";
        }

        private void cmbUserName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (userInfo.Tables[0].Rows.Count > 0)
            {
                selectedIndex = cmbUserName.SelectedIndex;
                UpdateUI(selectedIndex);
                selectedIndex = cmbUserName.SelectedIndex;
            }
        }

        // edit user's name, fullname, description, enable/disable, or lock/unlock
        private void btnEdit_Click(object sender, EventArgs e)
        {
            // set and save the old account attributes
            LocalUser oldUser = SetOldUser();
            // set and save the new account attributes
            LocalUser newUser = SetNewUser();

            // instantiate the UserMgr class
            UserMgr um = new UserMgr();
            um.ComputerName = computerName;

            // call the method to update current user's attributes
            string result = um.EditAccount(oldUser, newUser);
            // display the result on the status strip
            staUserMgr.Items[0].Text = result;
            userInfo.Tables[0].Clear();
            userInfo = um.GetAllLocalUsers();
            ResetUI();
        }

        // reset Password
        private void btnReset_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text.Equals(txtConfPassword.Text))
            {
                // instantiate the UserMgr class
                UserMgr um = new UserMgr();
                um.ComputerName = computerName;

                bool res = um.ResetPassword(cmbUserName.Text, txtConfPassword.Text);
                if (res)
                    staUserMgr.Items[0].Text = "Password is reset";
                else
                    MessageBox.Show("Problem with reset password");
            }
            else
            {
                staUserMgr.Items[0].Text = "Passwords don't match, please try again";
                txtPassword.Text = ""; txtConfPassword.Text = "";
            }
        }

        private LocalUser SetOldUser()
        {
            LocalUser oldUser = new LocalUser();
            DataRow row = userInfo.Tables[0].Rows[selectedIndex];
            // set old user attributes from the dataset
            oldUser.UserName = row["UserName"].ToString();
            oldUser.UserFullName = row["FullName"].ToString();
            oldUser.UserDescription = row["Description"].ToString();
            oldUser.PasswordChangeable = Convert.ToBoolean(row["PasswordChangeable"]);
            oldUser.PasswordExpires = Convert.ToBoolean(row["PasswordExpires"]);
            oldUser.PasswordLastSet = Convert.ToBoolean(row["PasswordLastSet"]);
            oldUser.AccountDisabled = Convert.ToBoolean(row["AccountDisabled"]);
            oldUser.AccountLocked = Convert.ToBoolean(row["AccountLocked"]);

            return oldUser;
        }

        private LocalUser SetNewUser()
        {
            LocalUser newUser = new LocalUser();
            newUser.UserName = cmbUserName.Text;
            newUser.UserFullName = txtFullName.Text;
            newUser.UserDescription = txtDescription.Text;
            newUser.AccountDisabled = chkAccountDisabled.Checked;
            newUser.AccountLocked = chkAccountLockout.Checked;
            newUser.PasswordLastSet = chkMustChangePswd.Checked;
            // notice the negation - Expires vs. Never expires
            // backwards due to wording - if the "User cannot Change password" is checked,
            // it means that "Password is not Changeable", set it to FALSE, and vices versa.
            newUser.PasswordChangeable = !chkCannotChangePswd.Checked;
            // backwards again as above - if the "Password never expires" is checked,
            // it means that Password is NOT going to expire, thus it is set to FALSE, and vices versa
            newUser.PasswordExpires = !chkPswdNeverExpires.Checked;

            return newUser;
        }

        private void ResetUI()
        {
            cmbUserName.Items.Clear();
            for (int i = 0; i < userInfo.Tables[0].Rows.Count; i++)
                cmbUserName.Items.Add(userInfo.Tables[0].Rows[i]["UserName"].ToString());
        }

        // handle mutually exclusiveness on these attributes
        private void chkMustChangePswd_CheckedChanged(object sender, EventArgs e)
        {
            TogglePswdExpiresCannotChangePswd();
        }

        private void chkCannotChangePswd_CheckedChanged(object sender, EventArgs e)
        {
            EnableDisableMustChangePassword();
        }

        private void chkPswdNeverExpires_CheckedChanged(object sender, EventArgs e)
        {
            EnableDisableMustChangePassword();
        }

        private void TogglePswdExpiresCannotChangePswd()
        {
            if (chkMustChangePswd.Checked)
            {
                chkCannotChangePswd.Enabled = false;
                chkPswdNeverExpires.Enabled = false;
                chkMustChangePswd.Enabled = true;
            }
            else
            {
                chkCannotChangePswd.Enabled = true;
                chkPswdNeverExpires.Enabled = true;
                chkMustChangePswd.Enabled = false;
            }
        }

        private void EnableDisableMustChangePassword()
        {
            if ((!chkCannotChangePswd.Checked) & (!chkPswdNeverExpires.Checked))
            {
                chkMustChangePswd.Enabled = true;
            }
            else
            {
                chkMustChangePswd.Enabled = false;
            }
        }
    }

}